#! /usr/bin/env python3
# -*- coding: utf-8-*

import cv2 as cv
import numpy as np


class Block_recognition:
    def __init__(self):
        self.video = cv.VideoCapture(0)
        self.sw = True
        self.pst = []
        self.num = 0
        self.hsv_color = []
        cv.namedWindow('image')
        cv.setMouseCallback("image",self.draw_circle)


    def draw_circle(self,event,x,y,flags,param):
        self.x = x
        self.y = y
        if event==cv.EVENT_LBUTTONDBLCLK and not self.sw:
            cv.circle(self.frame,(x,y),5,(0,0,255),-1) # 创建图像与窗口并将窗口与回䖲函数绑定
            self.num += 1
            self.pst.append([x,y])

    def roi_get(self):
        i = 0
        rec = False
        print("按下'a'拾取工作台区域，按下'Esc'退出")
        while (True):
            if self.sw:
                ret, self.frame = self.video.read()
            cv.imshow("image",self.frame)
            if self.frame is None:
                break
            key = cv.waitKey(33)
            if self.num == 4:
                cv.polylines(self.frame,[np.array(self.pst)],10,(255,255,255))
                rec = True
            if key == ord('a'):
                self.sw = False
                print("双击鼠标按如下顺序选择角点\n"
                      " (1)————————————————————(2)\n",
                      " |         200mm        |\n",
                      " |                      |\n",
                      " | 150mm                |\n",
                      " |                      |\n",
                      " |                      |\n",
                      "(4)————————————————————(3)\n")
            if key ==27:
                break
        if not ret:
            self.video.release()
        cv.destroyAllWindows()
        return rec, self.pst

    def nothing(self,x):
        pass

    def division(self,pst):
        pst_obs = np.float32([[0,0],[400,0],[400,300],[0,300]])
        pst_origin = np.float32(pst)
        Mat = cv.getPerspectiveTransform(pst_origin,pst_obs)
        #########################
        cv.namedWindow("image1")
        cv.createTrackbar("H", "image1", 0, 255, self.nothing)
        cv.createTrackbar("S", "image1", 0, 255, self.nothing)
        cv.createTrackbar("V", "image1", 0, 180, self.nothing)
        cv.createTrackbar("dH", "image1", 0, 255, self.nothing)
        cv.createTrackbar("dS", "image1", 0, 255, self.nothing)
        cv.createTrackbar("dV", "image1", 0, 180, self.nothing)
        #########################
        i = 0
        while(True):
            ret, self.frame = self.video.read()
            dst = cv.warpPerspective(self.frame, Mat, (400, 300))
            bin_dst = self.binaryzation(dst)
            cv.imshow('image',dst)
            cv.imshow('image1', bin_dst)
            key = cv.waitKey(33)
            if key == ord('s'):
                i+=1
                cv.imwrite('./images/image'+str(i)+'.jpg',dst)
                print('./images/image' + str(i) + '.jpg')
            if key == 27:
                break
        self.video.release()
        cv.destroyAllWindows()


    def binaryzation(self,image):
        h_1 = cv.getTrackbarPos("H", "image1")
        s_1 = cv.getTrackbarPos("S", "image1")
        v_1 = cv.getTrackbarPos("V", "image1")
        h_2 = cv.getTrackbarPos("dH", "image1")
        s_2 = cv.getTrackbarPos("dS", "image1")
        v_2 = cv.getTrackbarPos("dV", "image1")
        lower_color = np.uint8([h_1, s_1, v_1])
        upper_color = np.uint8([h_2, s_2, v_2])
        hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
        mask = cv.inRange(hsv, lower_color, upper_color)
        self.hsv_color = [[h_1, s_1, v_1], [h_2, s_2, v_2]]
        return mask


if __name__ == "__main__":
    br = Block_recognition()
    ret,pst = br.roi_get()
    if ret:
        br.division(pst)
    print(br.pst)
    print(br.hsv_color)

